<?php

namespace addons\yunfood\model;

use addons\yunfood\library\Logic;
use addons\yunfood\library\ModelTrait;
use think\Cache;
use think\Model;
use traits\model\SoftDelete;

/**
 * 门店模型
 */
class Shop extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yunfood_shop';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    public function scopeShow($query)
    {
        return $query->where('status', '=', self::STATUS_NORMAL);
    }

    // 封面
    public function getCoverUrlAttr($value, $data)
    {
        return cdnurl($value, true);
    }

    protected function getStartTimeTextAttr($value, $data)
    {
        return Logic::intToHourTime($data['start_time']);
    }

    protected function getEndTimeTextAttr($value, $data)
    {
        return Logic::intToHourTime($data['end_time']);
    }

    // 状态
    const STATUS_NORMAL = 1;
    const STATUS_HIDDEN = 2;

    public static function getStatusList()
    {
        return [self::STATUS_NORMAL => __('Normal'), self::STATUS_HIDDEN => __('屏蔽')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $optionList = self::getStatusList();

        return $optionList[$data['status']] ?? $data['status'];
    }

    // 门店状态
    const STATE_REST = 0;  // 已休息
    const STATE_ING  = 1;  // 营业中

    public function getStateAttr($value, $data)
    {
        $state = self::STATE_REST;
        $time = date('Gi');
        if ($data['start_time'] > $data['end_time']) {  // 营业到凌晨
            if ($data['start_time'] <= $time || $data['end_time'] > $time) {
                $state = self::STATE_ING;
            }
        } else {  // 正常营业
            if ($data['start_time'] <= $time && $time < $data['end_time']) {
                $state = self::STATE_ING;
            }
        }

        return $state;
    }

    // 获取select列表
    public static function getOptionList($where = [], $cache = false, $limit = true)
    {
        $callBack = function () use ($where, $limit) {
            $dataList = Shop::field(['id', 'name'])->where($where)->select();
            $result = array_column($dataList->toArray(), 'name', 'id');
            if (! $limit) {
                $result = ['0' => '不限'] + $result;
            }

            return $result;
        };
        if (! $cache) {
            return $callBack();
        }

        return Cache::remember('shopList:' . sha1(json_encode($where)), $callBack, 5);
    }
}
